package cn.ming.wfchat.app.main;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.king.zxing.Intents;
import com.lcw.library.imagepicker.ImagePicker;
import com.lcw.library.imagepicker.utils.MediaFileUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.OnClick;
import cn.ming.wfchat.R;
import cn.ming.wfchat.app.AppService;
import cn.ming.wfchat.app.dialog.DynamicListDialog;
import cn.ming.wfchat.app.dialog.LockScreenActivity;
import cn.ming.wfchat.app.dialog.VersionUpgradeDialog;
import cn.ming.wfchat.app.dynamic.activity.ReleaseDynamicActivity;
import cn.ming.wfchat.app.me.activity.model.VersionBean;
import cn.ming.wfchat.app.moment.third.beans.UserBean;
import cn.ming.wfchat.kit.IMConnectionStatusViewModel;
import cn.ming.wfchat.kit.IMServiceStatusViewModel;
import cn.ming.wfchat.kit.WfcBaseActivity;
import cn.ming.wfchat.kit.WfcScheme;
import cn.ming.wfchat.kit.WfcUIKit;
import cn.ming.wfchat.kit.channel.ChannelInfoActivity;
import cn.ming.wfchat.kit.contact.ContactListFragment;
import cn.ming.wfchat.kit.contact.ContactViewModel;
import cn.ming.wfchat.kit.contact.newfriend.SearchUserActivity;
import cn.ming.wfchat.kit.conversation.CreateConversationActivity;
import cn.ming.wfchat.kit.conversationlist.ConversationListFragment;
import cn.ming.wfchat.kit.conversationlist.ConversationListViewModel;
import cn.ming.wfchat.kit.conversationlist.ConversationListViewModelFactory;
import cn.ming.wfchat.kit.group.GroupInfoActivity;
import cn.ming.wfchat.kit.mm.TakePhotoActivity;
import cn.ming.wfchat.kit.qrcode.ScanQRCodeActivity;
import cn.ming.wfchat.kit.search.SearchPortalActivity;
import cn.ming.wfchat.kit.user.ChangeMyNameActivity;
import cn.ming.wfchat.kit.user.UserInfoActivity;
import cn.ming.wfchat.kit.user.UserViewModel;
import cn.ming.wfchat.kit.utils.GlideLoader;
import cn.ming.wfchat.kit.utils.Tools;
import cn.ming.wfchat.kit.viewmodel.MessageViewModel;
import cn.ming.wfchat.kit.widget.ViewPagerFixed;
import cn.wildfirechat.client.ConnectionStatus;
import cn.wildfirechat.message.Message;
import cn.wildfirechat.message.core.MessageContentType;
import cn.wildfirechat.message.core.MessageStatus;
import cn.wildfirechat.model.Conversation;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;
import q.rorbin.badgeview.QBadgeView;

public class MainActivity extends WfcBaseActivity implements ViewPager.OnPageChangeListener {

    private List<Fragment> mFragmentList = new ArrayList<>(4);

    @BindView(R.id.bottomNavigationView)
    BottomNavigationView bottomNavigationView;
    @BindView(R.id.contentViewPager)
    ViewPagerFixed contentViewPager;
    @BindView(R.id.startingTextView)
    TextView startingTextView;
    @BindView(R.id.contentLinearLayout)
    LinearLayout contentLinearLayout;

    private QBadgeView unreadMessageUnreadBadgeView;
    private QBadgeView unreadFriendRequestBadgeView;
    private QBadgeView discoveryBadgeView;

    private static final int REQUEST_CODE_SCAN_QR_CODE = 100;
    private static final int REQUEST_IGNORE_BATTERY_CODE = 101;
    private static final int CAPTURE_IMAGE_SMALLVIDEO_ACTIVITY_REQUEST_CODE = 103;
    private static final int REQUEST_CODE_PUBLISH_FEED = 104;
    private static final int REQUEST_CODE_PICK_PHOTO = 105;

    private boolean isInitialized = false;

    private ContactListFragment contactListFragment;

    private ContactViewModel contactViewModel;
    private ConversationListViewModel conversationListViewModel;

    private Observer<Boolean> imStatusLiveDataObserver = status -> {
        if (status && !isInitialized) {
            init();
            isInitialized = true;
        }
    };
    private static final int REQUEST_CODE_PICK_IMAGE = 102;
    private SharedPreferences sp;

    @Override
    protected int contentLayout() {
        return R.layout.main_activity;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (contactViewModel != null) {
            contactViewModel.reloadFriendRequestStatus();
            conversationListViewModel.reloadConversationUnreadStatus();
        }
        updateMomentBadgeView();
        checkVersion();
    }

    @Override
    protected void afterViews() {
        sp = getSharedPreferences("config", Context.MODE_PRIVATE);
        bottomNavigationView.setItemIconTintList(null);
        IMServiceStatusViewModel imServiceStatusViewModel = ViewModelProviders.of(this).get(IMServiceStatusViewModel.class);
        imServiceStatusViewModel.imServiceStatusLiveData().observe(this, imStatusLiveDataObserver);
        IMConnectionStatusViewModel connectionStatusViewModel = ViewModelProviders.of(this).get(IMConnectionStatusViewModel.class);
        connectionStatusViewModel.connectionStatusLiveData().observe(this, status -> {
            if (status == ConnectionStatus.ConnectionStatusTokenIncorrect || status == ConnectionStatus.ConnectionStatusSecretKeyMismatch || status == ConnectionStatus.ConnectionStatusRejected || status == ConnectionStatus.ConnectionStatusLogout) {
                ChatManager.Instance().disconnect(true, true);
                reLogin();
            }
        });
        MessageViewModel messageViewModel = ViewModelProviders.of(this).get(MessageViewModel.class);
        messageViewModel.messageLiveData().observe(this, uiMessage -> {
            if (uiMessage.message.content.getType() == MessageContentType.MESSAGE_CONTENT_TYPE_FEED
                    || uiMessage.message.content.getType() == MessageContentType.MESSAGE_CONTENT_TYPE_FEED_COMMENT) {
                updateMomentBadgeView();
            }
        });

    }

    private void reLogin() {
        sp.edit().clear().apply();
        Intent intent = new Intent(this, SplashActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }


    private void init() {
        initView();
        conversationListViewModel = ViewModelProviders
                .of(this, new ConversationListViewModelFactory(Arrays.asList(Conversation.ConversationType.Single, Conversation.ConversationType.Group, Conversation.ConversationType.Channel), Arrays.asList(0)))
                .get(ConversationListViewModel.class);
        conversationListViewModel.unreadCountLiveData().observe(this, unreadCount -> {

            if (unreadCount != null && unreadCount.unread > 0) {
                showUnreadMessageBadgeView(unreadCount.unread);
            } else {
                hideUnreadMessageBadgeView();
            }
        });

        contactViewModel = ViewModelProviders.of(this).get(ContactViewModel.class);
        contactViewModel.friendRequestUpdatedLiveData().observe(this, count -> {
            if (count == null || count == 0) {
                hideUnreadFriendRequestBadgeView();
            } else {
                showUnreadFriendRequestBadgeView(count);
            }
        });

        if (checkDisplayName()) {
            ignoreBatteryOption();
        }

    }

    private void showUnreadMessageBadgeView(int count) {
        if (unreadMessageUnreadBadgeView == null) {
            BottomNavigationMenuView bottomNavigationMenuView = ((BottomNavigationMenuView) bottomNavigationView.getChildAt(0));
            View view = bottomNavigationMenuView.getChildAt(0);
            unreadMessageUnreadBadgeView = new QBadgeView(MainActivity.this);
            unreadMessageUnreadBadgeView.bindTarget(view);
        }
        unreadMessageUnreadBadgeView.setBadgeNumber(count);
    }

    private void hideUnreadMessageBadgeView() {
        if (unreadMessageUnreadBadgeView != null) {
            unreadMessageUnreadBadgeView.hide(true);
            unreadMessageUnreadBadgeView = null;
        }
    }

    private void updateMomentBadgeView() {
        if (!WfcUIKit.getWfcUIKit().isSupportMoment()) {
            return;
        }
        List<Message> messages = ChatManager.Instance().getMessagesEx2(Collections.singletonList(Conversation.ConversationType.Single), Collections.singletonList(1), MessageStatus.Unread, 0, true, 100, null);
        int count = messages == null ? 0 : messages.size();
        if (count > 0) {
            if (discoveryBadgeView == null) {
                BottomNavigationMenuView bottomNavigationMenuView = ((BottomNavigationMenuView) bottomNavigationView.getChildAt(0));
                View view = bottomNavigationMenuView.getChildAt(2);
                discoveryBadgeView = new QBadgeView(MainActivity.this);
                discoveryBadgeView.bindTarget(view);
            }
            discoveryBadgeView.setBadgeNumber(count);
        } else {
            if (discoveryBadgeView != null) {
                discoveryBadgeView.hide(true);
                discoveryBadgeView = null;
            }
        }
    }


    private void showUnreadFriendRequestBadgeView(int count) {
        if (unreadFriendRequestBadgeView == null) {
            BottomNavigationMenuView bottomNavigationMenuView = ((BottomNavigationMenuView) bottomNavigationView.getChildAt(0));
            View view = bottomNavigationMenuView.getChildAt(1);
            unreadFriendRequestBadgeView = new QBadgeView(MainActivity.this);
            unreadFriendRequestBadgeView.bindTarget(view);
        }
        unreadFriendRequestBadgeView.setBadgeNumber(count);
    }

    public void hideUnreadFriendRequestBadgeView() {
        if (unreadFriendRequestBadgeView != null) {
            unreadFriendRequestBadgeView.hide(true);
            unreadFriendRequestBadgeView = null;
        }
    }

    @Override
    protected int menu() {
        return R.menu.main;
    }

    @Override
    protected boolean showHomeMenuItem() {
        return false;
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    private void initView() {
        setTitle("聊天");

        startingTextView.setVisibility(View.GONE);
        contentLinearLayout.setVisibility(View.VISIBLE);

        //设置ViewPager的最大缓存页面
        contentViewPager.setOffscreenPageLimit(3);

        ConversationListFragment conversationListFragment = new ConversationListFragment();
        contactListFragment = new ContactListFragment();
        DiscoveryFragment discoveryFragment = new DiscoveryFragment();
        MeFragment meFragment = new MeFragment();
        NetWorkFragment netWorkFragment = new NetWorkFragment();
        mFragmentList.add(conversationListFragment);
        mFragmentList.add(contactListFragment);
        mFragmentList.add(netWorkFragment);
        mFragmentList.add(discoveryFragment);
        mFragmentList.add(meFragment);
        contentViewPager.setAdapter(new HomeFragmentPagerAdapter(getSupportFragmentManager(), mFragmentList));
        contentViewPager.setOnPageChangeListener(this);

        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            Menu menu = toolbar.getMenu();
            switch (item.getItemId()) {
                case R.id.conversation_list:
                    contentViewPager.setCurrentItem(0);
                    setTitle("聊天");
                    if (!isDarkTheme()) {
                        setTitleBackgroundResource(R.color.gray5, false);
                    }
                    menu.setGroupVisible(0, true);
                    tvRight.setVisibility(View.GONE);
                    break;
                case R.id.contact:
                    contentViewPager.setCurrentItem(1);
                    setTitle("好友");
                    if (!isDarkTheme()) {
                        setTitleBackgroundResource(R.color.gray5, false);
                    }
                    menu.setGroupVisible(0, true);
                    tvRight.setVisibility(View.GONE);
                    break;
                case R.id.network:
                    contentViewPager.setCurrentItem(2);
                    setTitle("关系网");
                    if (!isDarkTheme()) {
                        setTitleBackgroundResource(R.color.gray5, false);
                    }
                    menu.setGroupVisible(0, false);
                    tvRight.setVisibility(View.GONE);
                    break;
                case R.id.discovery:
                    contentViewPager.setCurrentItem(3);
                    setTitle("动态");
                    if (!isDarkTheme()) {
                        setTitleBackgroundResource(R.color.gray5, false);
                    }
                    menu.setGroupVisible(0, false);
                    setTvRight("发布动态");
                    break;
                case R.id.me:
                    contentViewPager.setCurrentItem(4);
                    setTitle("我的");
                    if (!isDarkTheme()) {
                        setTitleBackgroundResource(R.color.white, false);
                    }
                    menu.setGroupVisible(0, true);
                    tvRight.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
            return true;
        });
        if (ChatManager.isLockPasswordEnable()) {
//            if (MyApp.lockScreenDialog.getDialog() == null) {
//                MyApp.lockScreenDialog.show(MainActivity.this);
//            }
            Tools.jump(MainActivity.this, LockScreenActivity.class,false);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.search:
                showSearchPortal();
                break;
            case R.id.chat:
                createConversation();
                break;
            case R.id.add_contact:
                searchUser();
                break;
            case R.id.scan_qrcode:
                String[] permissions = new String[]{Manifest.permission.CAMERA};
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (!checkPermission(permissions)) {
                        requestPermissions(permissions, 100);
                        return true;
                    }
                }
                startActivityForResult(new Intent(this, ScanQRCodeActivity.class), REQUEST_CODE_SCAN_QR_CODE);
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showSearchPortal() {
        Intent intent = new Intent(this, SearchPortalActivity.class);
        startActivity(intent);
    }

    private void createConversation() {
        Intent intent = new Intent(this, CreateConversationActivity.class);
        startActivity(intent);
    }

    private void searchUser() {
        Intent intent = new Intent(this, SearchUserActivity.class);
        startActivity(intent);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case 0:
                bottomNavigationView.setSelectedItemId(R.id.conversation_list);
                break;
            case 1:
                bottomNavigationView.setSelectedItemId(R.id.contact);
                break;
            case 2:
                bottomNavigationView.setSelectedItemId(R.id.network);
                break;
            case 3:
                bottomNavigationView.setSelectedItemId(R.id.discovery);
                break;
            case 4:
                bottomNavigationView.setSelectedItemId(R.id.me);
                break;
            default:
                break;
        }
        contactListFragment.showQuickIndexBar(position == 1);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (state != ViewPager.SCROLL_STATE_IDLE) {
            //滚动过程中隐藏快速导航条
            contactListFragment.showQuickIndexBar(false);
        } else {
            contactListFragment.showQuickIndexBar(true);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_SCAN_QR_CODE:
                if (resultCode == RESULT_OK) {
                    String result = data.getStringExtra(Intents.Scan.RESULT);
                    onScanPcQrCode(result);
                }
                break;
            case REQUEST_IGNORE_BATTERY_CODE:
                if (resultCode == RESULT_CANCELED) {
                    Toast.makeText(this, "允许野火IM后台运行，更能保证消息的实时性", Toast.LENGTH_SHORT).show();
                }
                break;
            case REQUEST_CODE_PICK_IMAGE:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        data.setClass(MainActivity.this, ReleaseDynamicActivity.class);
                        startActivity(data);
                    }
                }
            case CAPTURE_IMAGE_SMALLVIDEO_ACTIVITY_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    String path = data.getStringExtra("path");
                    boolean take_photo = data.getBooleanExtra("take_photo", false);
                    if (TextUtils.isEmpty(path)) {
                        Toast.makeText(this, "拍照错误, 请向我们反馈", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    Intent intent = new Intent(this, ReleaseDynamicActivity.class);
                    if (take_photo) {
                        ArrayList<String> imageUrls = new ArrayList<>();
                        imageUrls.add(path);
                        intent.putExtra(ReleaseDynamicActivity.IMAGE_URLS, imageUrls);
                    } else {
                        intent.putExtra(ReleaseDynamicActivity.VIDEO_URL, path);
                    }
                    startActivityForResult(intent, REQUEST_CODE_PUBLISH_FEED);
                }
            case REQUEST_CODE_PICK_PHOTO:
                if (resultCode == RESULT_OK) {
                    List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
                    if (imagePaths == null || imagePaths.isEmpty()) {
                        return;
                    }
                    ArrayList<String> imageUrls = new ArrayList<>();
                    Intent intent = new Intent(this, ReleaseDynamicActivity.class);
                    if (MediaFileUtil.isVideoFileType(imagePaths.get(0))) {
                        //如果是视频
                        intent.putExtra(ReleaseDynamicActivity.VIDEO_URL, imagePaths.get(0));
                    } else {
                        for (String imageItem : imagePaths) {
                            imageUrls.add(imageItem);
                        }
                        intent.putExtra(ReleaseDynamicActivity.IMAGE_URLS, imageUrls);
                    }
                    startActivityForResult(intent, REQUEST_CODE_PUBLISH_FEED);
                }
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100 && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startActivityForResult(new Intent(this, ScanQRCodeActivity.class), REQUEST_CODE_SCAN_QR_CODE);
        } else if (requestCode == 101 && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Intent intent = new Intent(MainActivity.this, TakePhotoActivity.class);
            intent.putExtra(TakePhotoActivity.MODE, TakePhotoActivity.MODE_CAPTURE_AND_RECORDER);
            startActivityForResult(intent, CAPTURE_IMAGE_SMALLVIDEO_ACTIVITY_REQUEST_CODE);
        }
    }

    private void onScanPcQrCode(String qrcode) {
        String prefix = qrcode.substring(0, qrcode.lastIndexOf('/') + 1);
        String value = qrcode.substring(qrcode.lastIndexOf("/") + 1);
        if (prefix.equals(WfcScheme.QR_CODE_PREFIX_PC_SESSION)) {
            pcLogin(value);
        } else if (prefix.equals(WfcScheme.QR_CODE_PREFIX_USER)) {
            showUser(value);
        } else if (prefix.equals(WfcScheme.QR_CODE_PREFIX_GROUP)) {
            joinGroup(value);
        } else if (prefix.equals(WfcScheme.QR_CODE_PREFIX_CHANNEL)) {
            subscribeChannel(value);
        } else {
            Toast.makeText(this, "qrcode: " + qrcode, Toast.LENGTH_SHORT).show();
        }
//        switch (prefix) {
//            case WfcScheme.QR_CODE_PREFIX_PC_SESSION:
//                pcLogin(value);
//                break;
//            case WfcScheme.QR_CODE_PREFIX_USER:
//                showUser(value);
//                break;
//            case WfcScheme.QR_CODE_PREFIX_GROUP:
//                joinGroup(value);
//                break;
//            case WfcScheme.QR_CODE_PREFIX_CHANNEL:
//                subscribeChannel(value);
//                break;
//            default:
//                Toast.makeText(this, "qrcode: " + qrcode, Toast.LENGTH_SHORT).show();
//                break;
//        }
    }

    private void pcLogin(String token) {
        Intent intent = new Intent(this, PCLoginActivity.class);
        intent.putExtra("token", token);
        startActivity(intent);
    }

    private void showUser(String mobile) {
        AppService.Instance().getInfoByMobile(mobile, new AppService.InfoByMobileCallback() {
            @Override
            public void onUiSuccess(UserBean assetsBean) {
                UserViewModel userViewModel = ViewModelProviders.of(MainActivity.this).get(UserViewModel.class);
                UserInfo userInfo = userViewModel.getUserInfo(assetsBean.getUserId(), true);
                if (userInfo == null) {
                    return;
                }
                Intent intent = new Intent(MainActivity.this, UserInfoActivity.class);
                intent.putExtra("userInfo", userInfo);
                startActivity(intent);
            }

            @Override
            public void onUiFailure(int code, String msg) {
                ChatManager.showToast(msg);

            }
        });
    }

    private void joinGroup(String groupId) {
        Intent intent = new Intent(this, GroupInfoActivity.class);
        intent.putExtra("groupId", groupId);
        startActivity(intent);
    }

    private void subscribeChannel(String channelId) {
        Intent intent = new Intent(this, ChannelInfoActivity.class);
        intent.putExtra("channelId", channelId);
        startActivity(intent);
    }

    private boolean checkDisplayName() {
        UserViewModel userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
        SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
        UserInfo userInfo = userViewModel.getUserInfo(userViewModel.getUserId(), false);
        if (userInfo != null && TextUtils.equals(userInfo.displayName, userInfo.mobile)) {
            if (!sp.getBoolean("updatedDisplayName", false)) {
                sp.edit().putBoolean("updatedDisplayName", true).apply();
                updateDisplayName();
                return false;
            }
        }
        return true;
    }

    private void updateDisplayName() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .content("修改个人昵称？")
                .positiveText("修改")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        Intent intent = new Intent(MainActivity.this, ChangeMyNameActivity.class);
                        startActivity(intent);
                    }
                }).build();
        dialog.show();
    }


    private void ignoreBatteryOption() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                Intent intent = new Intent();
                String packageName = getPackageName();
                PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                    intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                    intent.setData(Uri.parse("package:" + packageName));
                    startActivityForResult(intent, REQUEST_IGNORE_BATTERY_CODE);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @OnClick(R.id.tv_right)
    void setRight() {
        DynamicListDialog.newInstance().setOnClickListener(new DynamicListDialog.OnClickListener() {
            @Override
            public void goText() {
                Intent intent = new Intent(MainActivity.this, ReleaseDynamicActivity.class);
                startActivity(intent);
            }

            @Override
            public void goPhoto() {
//                Intent intent = ImagePicker.picker().showCamera(true).enableMultiMode(9).buildPickIntent(MainActivity.this);
//                startActivityForResult(intent, REQUEST_CODE_PICK_PHOTO);
                ImagePicker.getInstance()
                        .showImage(true)//设置是否展示图片
                        .showVideo(true)//设置是否展示视频
                        .setSingleType(true)//设置图片视频不能同时选择
                        .setMaxCount(9)//设置最大选择图片数目(默认为1，单选)
                        .setImageLoader(new GlideLoader(MainActivity.this))
                        .start(MainActivity.this, REQUEST_CODE_PICK_PHOTO);
            }

            @Override
            public void goShooting() {
                String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.MODIFY_AUDIO_SETTINGS, Manifest.permission.RECORD_AUDIO};
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (!checkPermission(permissions)) {
                        requestPermissions(permissions, 101);
                        return;
                    }
                }
                Intent intent = new Intent(MainActivity.this, TakePhotoActivity.class);
                intent.putExtra(TakePhotoActivity.MODE, TakePhotoActivity.MODE_CAPTURE_AND_RECORDER);
                startActivityForResult(intent, CAPTURE_IMAGE_SMALLVIDEO_ACTIVITY_REQUEST_CODE);


            }
        }).show(MainActivity.this);
    }

    void checkVersion() {
        AppService.Instance().checkVersion(new AppService.ChackVersionCallback() {
            @Override
            public void onUiSuccess(VersionBean assetsBean) {
                if (assetsBean.getUpdateType() == 1) {
                    VersionUpgradeDialog.newInstance(assetsBean).show(MainActivity.this);
                } else {
                    long quxiaotime = System.currentTimeMillis();
                    if (sp.getLong("quxiaotime", 0) == 0 ||
                            sp.getLong("quxiaotime", 0) - quxiaotime > 24 * 60 * 1000) {
                        VersionUpgradeDialog.newInstance(assetsBean).show(MainActivity.this);
                    }
                }

            }

            @Override
            public void onUiFailure(int code, String msg) {
                //ChatManager.showToast(msg);
            }
        });
    }
}
